﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;

namespace XamlMvp.Controls
{
    public class MvpControl : UserControl, IView
    {
        bool initialLayout = true;

        public bool IsAutoEventWireUp { get { return View.GetAutoEventWireUp(this); } }

        public MvpControl() : base()
        {
            this.LayoutUpdated += OnLayoutUpdated;
            this.Unloaded += OnUnloaded;
        }

        void OnLayoutUpdated(object sender, EventArgs e)
        {
            if (initialLayout)
            {
                Binders.Presenters.Bind(this);
                initialLayout = false;
            }
        }
        IDispatcher dispatcher;
        IDispatcher IView.Dispatcher
        {
            get 
            {
                if (dispatcher == null)
                {
                    Interlocked.Exchange(ref dispatcher, new DispatcherWrapper(base.Dispatcher));
                }
                return dispatcher;
            }
        }

        void OnUnloaded(object sender, RoutedEventArgs e)
        {
            LayoutUpdated -= OnLayoutUpdated;
            Unloaded -= OnUnloaded;
        }
    }
}
